import { Injectable } from '@nestjs/common';
import { HdWallet } from "./entity";
import axios from "axios";
import { ethers } from "ethers";
import * as dotenv from "dotenv";

dotenv.config();
const RPC_URL = process.env.POLYGON_RPC_URL;
const PRIVATE_KEY = process.env.PRIVATE_KEY;

@Injectable()
export class WalletService {

  createWallet(network: string,password: string) {
    return HdWallet.getInstance().create(network,password)
  }

  recoverWallet(network: string,mnemonic: string, password: string) {
    return HdWallet.getInstance().recover(network,mnemonic,password)
  }

  createAccount(index: number) {
    return HdWallet.getInstance().createAccount(index)
  }

  setNetwork(network:string){
    HdWallet.getInstance().setNetwork(network);
  }

  sendTransaction(toAddress: string, amount: number){
    HdWallet.getInstance().sendTransaction(toAddress,amount);
  }

  async getBalance(): Promise<bigint> {
    const provider = ethers.getDefaultProvider(RPC_URL);
    const signer = new ethers.Wallet(PRIVATE_KEY,provider);
    return await provider.getBalance(signer.address);
  }

  async getBitcoinBlockHeight(): Promise<number> {
    const rpcUrl = 'https://btc.getblock.io/64d4e7a3-0832-47fd-8a05-1cc4b000fd30/testnet/'; // 比特币节点的 RPC 地址
    //构造RPC请求数据
    const rpcData = {
      jsonrpc: '1.0',
      method: 'getblockcount',
      params: [],
      id: 'getBlockCount',
    };
    //发送RPC请求
    const response = await axios.post(rpcUrl, rpcData);
    //解析返回的数据获取区块高度
    const blockHeight = response.data.result;
    return blockHeight;
  }



}
